import { Approval, ApprovalStatus, ApprovalStatusText, ApprovalType } from '../../types/index';
import { getApprovalDetail, handleApproval, currentUser, getApprovalType } from '../../services/mockData';

Page({
  data: {
    approval: null as Approval | null,
    approvalType: null as ApprovalType | null,
    showActionSheet: false,
    canApprove: false,
    statusText: ApprovalStatusText,
    transferTargets: [
      { id: 'user002', name: '李四' },
      { id: 'user003', name: '王五' }
    ]
  },

  async onLoad(options: any) {
    if (options.id) {
      await this.loadApprovalDetail(options.id);
    }
  },

  async loadApprovalDetail(id: string) {
    const approval = await getApprovalDetail(id);
    if (approval) {
      const canApprove = approval.status === ApprovalStatus.PENDING && 
                        approval.currentApprover.id === currentUser.id;
      
      // 获取审批类型定义
      let approvalType = null;
      if (approval.formData) {
        approvalType = await getApprovalType(approval.type);
      }

      this.setData({ 
        approval,
        approvalType,
        canApprove
      });
    }
  },

  async handleApprove() {
    if (!this.data.approval) return;
    const result = await handleApproval(
      this.data.approval.id,
      ApprovalStatus.APPROVED,
      '同意'
    );
    if (result) {
      wx.showToast({ 
        title: '已同意', 
        icon: 'success',
        success: () => {
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }
      });
    }
  },

  async handleReject() {
    if (!this.data.approval) return;
    const result = await handleApproval(
      this.data.approval.id,
      ApprovalStatus.REJECTED,
      '拒绝'
    );
    if (result) {
      wx.showToast({ 
        title: '已拒绝', 
        icon: 'success',
        success: () => {
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }
      });
    }
  },

  showTransfer() {
    this.setData({ showActionSheet: true });
  },

  hideActionSheet() {
    this.setData({ showActionSheet: false });
  },

  async handleTransfer(e: any) {
    const { userid: targetUserId, username: targetUserName } = e.currentTarget.dataset;
    if (!this.data.approval) return;
    
    const result = await handleApproval(
      this.data.approval.id,
      ApprovalStatus.TRANSFERRED,
      `已转交给${targetUserName}`
    );
    
    if (result) {
      this.setData({ showActionSheet: false });
      wx.showToast({ 
        title: '已转交', 
        icon: 'success',
        success: () => {
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }
      });
    }
  },

  // 获取选项标签
  getOptionLabel(options: Array<{ value: string; label: string }> | undefined, value: string): string {
    if (!options) return value;
    const option = options.find(opt => opt.value === value);
    return option ? option.label : value;
  }
}); 